package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.item.bo.SpuBO;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.bo.SpuBO;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.mapper.StockMapper;
import com.leyou.item.pojo.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @Author: taft
 * @Date: 2018-10-13 11:56
 */
@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    Logger logger = LoggerFactory.getLogger(GoodsService.class);

    public PageResult<SpuBO> querySpuByPage(String key, Boolean saleable, Integer page, Integer rows) {

        //分页查询
        PageHelper.startPage(page, rows);


        //构建查询条件
        Example example = new Example(Spu.class);

        Example.Criteria criteria = example.createCriteria();

        //如果key不为空要根据key查询
        if (null != key) {
            criteria.andLike("title","%"+key+"%");
        }


        //如果saleable不为空要根据saleable查询
        if (saleable!=null){
            criteria.andEqualTo("saleable",saleable);
        }


        //执行查询
        Page<Spu> spus = (Page<Spu>) spuMapper.selectByExample(example);

        //把spu转成SPUBO

        List<SpuBO> spuBOList = new ArrayList<>();
        for (Spu spu : spus.getResult()) {
            SpuBO spuBO = new SpuBO();
            BeanUtils.copyProperties(spu,spuBO);
            //TODO SpuBO中 缺少cname以及bname
            spuBO.setBname(brandService.queryBrandById(spu.getBrandId()).getName());

            // 2、查询spu的商品分类名称,要查三级分类
            List<String> names = this.categoryService.queryNamesByIds(
                    Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));

            spuBO.setCname(StringUtils.join(names,"/"));

            spuBOList.add(spuBO);
        }


        return new PageResult<>(spus.getTotal(),new Long(spus.getPages()),spuBOList);
    }

    @Transactional
    public void saveGoods(SpuBO spuBO) {

        //给spu添加默认属性
        spuBO.setCreateTime(new Date());

        spuBO.setLastUpdateTime(spuBO.getCreateTime());

        spuBO.setSaleable(true);

        spuBO.setValid(true);

        //保存spu
        this.spuMapper.insert(spuBO);

        //保存spuDetail
        SpuDetail spuDetail = spuBO.getSpuDetail();
        spuDetail.setSpuId(spuBO.getId());

        this.spuDetailMapper.insert(spuDetail);

        //保存sku 以及stock
        List<Sku> skus = spuBO.getSkus();

        skus.forEach(sku -> {
            sku.setSpuId(spuBO.getId());
            sku.setLastUpdateTime(spuBO.getLastUpdateTime());
            sku.setCreateTime(spuBO.getCreateTime());
            this.skuMapper.insert(sku);

            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());

            this.stockMapper.insert(stock);
        });


        //给rabbitMQ发送数据，指定交换机名称，routingkey，消息体
        this.sendMessage(spuBO.getId(),"insert");

    }

    public SpuDetail querySpuDetailById(Long spuId) {
        return this.spuDetailMapper.selectByPrimaryKey(spuId);
    }


    public List<Sku> querySkuBySpuId(Long spuId) {

        Sku sku = new Sku();
        sku.setSpuId(spuId);

        List<Sku> skus = this.skuMapper.select(sku);

        skus.forEach(sku1 -> {
            Stock stock = new Stock();
            stock.setSkuId(sku1.getId());
            //由于sku和stock是一对一的所以一个sku的id只能查到一个stock
            sku1.setStock(this.stockMapper.select(stock).get(0).getStock());

        });
        return skus;
    }

    public void updateGoods(SpuBO spuBO) {
        //判断sku是否有id如果没有，直接调用saveGoods中保存sku的方法

        //判断如果skuId有值，表示update

        //数据（3个既有id）库中的spuId对应的sku（一个id）比当前修改的多

        //这种情况，那两个多的sku表示已经废弃，需要把其对应的enable改为false

        this.sendMessage(spuBO.getId(),"update");
    }

    public Spu querySpuById(Long id) {
        return this.spuMapper.selectByPrimaryKey(id);
    }


    private void sendMessage(Long id, String type){
        // 发送消息
        try {
            this.amqpTemplate.convertAndSend("item." + type, id);
        } catch (Exception e) {
            logger.error("{}商品消息发送异常，商品id：{}", type, id, e);
        }
    }

    public Sku querySkuByIds(Long skuId) {
     return skuMapper.selectByPrimaryKey(skuId);
    }

    public Sku querySkuById(Long id) {
        return this.skuMapper.selectByPrimaryKey(id);
    }

    public Map<String, List<Cart>> queryAll() {
        List<Sku> skuList = this.skuMapper.selectAll();
        List<Cart> skuList1 = new ArrayList<>();
        List<Cart> skuList2 = new ArrayList<>();
        List<Cart> skuList3 = new ArrayList<>();
        List<Cart> skuList4 = new ArrayList<>();
        List<Cart> skuList5 = new ArrayList<>();
        int i1 = 10;
        int i2 = 100;
        int i3 = 200;
        int i4 = 300;
        int i5 = 400;
        for (int i = 0; i < 4; i++) {

            Cart cart = new Cart();
            cart.setImage(skuList.get(i1).getImages());
            cart.setOwnSpec(skuList.get(i1).getOwnSpec());
            cart.setPrice(skuList.get(i1).getPrice());
            cart.setSkuId(skuList.get(i1).getId());
            cart.setTitle(skuList.get(i1).getTitle());
            cart.setSpuId(skuList.get(i1).getSpuId());
            cart.setNum(1);
            skuList1.add(cart);


            Cart cart2 = new Cart();
            cart2.setImage(skuList.get(i2).getImages());
            cart2.setOwnSpec(skuList.get(i2).getOwnSpec());
            cart2.setPrice(skuList.get(i2).getPrice());
            cart2.setSkuId(skuList.get(i2).getId());
            cart2.setTitle(skuList.get(i2).getTitle());
            cart2.setSpuId(skuList.get(i2).getSpuId());
            cart2.setNum(1);
            skuList2.add(cart2);


            Cart cart3 = new Cart();
            cart3.setImage(skuList.get(i3).getImages());
            cart3.setOwnSpec(skuList.get(i3).getOwnSpec());
            cart3.setPrice(skuList.get(i3).getPrice());
            cart3.setSkuId(skuList.get(i3).getId());
            cart3.setTitle(skuList.get(i3).getTitle());
            cart3.setSpuId(skuList.get(i3).getSpuId());
            cart3.setNum(1);
            skuList3.add(cart3);


            Cart cart4 = new Cart();
            cart4.setImage(skuList.get(i4).getImages());
            cart4.setOwnSpec(skuList.get(i4).getOwnSpec());
            cart4.setPrice(skuList.get(i4).getPrice());
            cart4.setSkuId(skuList.get(i4).getId());
            cart4.setTitle(skuList.get(i4).getTitle());
            cart4.setSpuId(skuList.get(i4).getSpuId());
            cart4.setNum(1);
            skuList4.add(cart4);


            Cart cart5 = new Cart();
            cart5.setImage(skuList.get(i5).getImages());
            cart5.setOwnSpec(skuList.get(i5).getOwnSpec());
            cart5.setPrice(skuList.get(i5).getPrice());
            cart5.setSkuId(skuList.get(i5).getId());
            cart5.setTitle(skuList.get(i5).getTitle());
            cart5.setSpuId(skuList.get(i5).getSpuId());
            cart5.setNum(1);
            skuList5.add(cart5);

            i1 += 10;
            i2 += 40;
            i3 += 10;
            i4 += 10;
            i5 += 10;
        }

        Map<String, List<Cart>> resultMap = new HashMap<>();
        resultMap.put("skus1", skuList1);
        resultMap.put("skus2", skuList2);
        resultMap.put("skus3", skuList3);
        resultMap.put("skus4", skuList4);
        resultMap.put("skus5", skuList5);
        return resultMap;
    }

    public Map<String, List<Cart>> queryAll2() {
        List<Sku> skuList = this.skuMapper.selectAll();
        List<Cart> skuList1 = new ArrayList<>();
        List<Cart> skuList2 = new ArrayList<>();
        List<Cart> skuList3 = new ArrayList<>();
        List<Cart> skuList4 = new ArrayList<>();
        List<Cart> skuList5 = new ArrayList<>();
        int i1 = 70;
        int i2 = 170;
        int i3 = 270;
        int i4 = 370;
        int i5 = 470;
        for (int i = 0; i < 2; i++) {

            Cart cart = new Cart();
            cart.setImage(skuList.get(i1).getImages());
            cart.setOwnSpec(skuList.get(i1).getOwnSpec());
            cart.setPrice(skuList.get(i1).getPrice());
            cart.setSkuId(skuList.get(i1).getId());
            cart.setTitle(skuList.get(i1).getTitle());
            cart.setSpuId(skuList.get(i1).getSpuId());
            cart.setNum(1);
            skuList1.add(cart);


            Cart cart2 = new Cart();
            cart2.setImage(skuList.get(i2).getImages());
            cart2.setOwnSpec(skuList.get(i2).getOwnSpec());
            cart2.setPrice(skuList.get(i2).getPrice());
            cart2.setSkuId(skuList.get(i2).getId());
            cart2.setTitle(skuList.get(i2).getTitle());
            cart2.setSpuId(skuList.get(i2).getSpuId());
            cart2.setNum(1);
            skuList2.add(cart2);


            Cart cart3 = new Cart();
            cart3.setImage(skuList.get(i3).getImages());
            cart3.setOwnSpec(skuList.get(i3).getOwnSpec());
            cart3.setPrice(skuList.get(i3).getPrice());
            cart3.setSkuId(skuList.get(i3).getId());
            cart3.setTitle(skuList.get(i3).getTitle());
            cart3.setSpuId(skuList.get(i3).getSpuId());
            cart3.setNum(1);
            skuList3.add(cart3);


            Cart cart4 = new Cart();
            cart4.setImage(skuList.get(i4).getImages());
            cart4.setOwnSpec(skuList.get(i4).getOwnSpec());
            cart4.setPrice(skuList.get(i4).getPrice());
            cart4.setSkuId(skuList.get(i4).getId());
            cart4.setTitle(skuList.get(i4).getTitle());
            cart4.setSpuId(skuList.get(i4).getSpuId());
            cart4.setNum(1);
            skuList4.add(cart4);


            Cart cart5 = new Cart();
            cart5.setImage(skuList.get(i5).getImages());
            cart5.setOwnSpec(skuList.get(i5).getOwnSpec());
            cart5.setPrice(skuList.get(i5).getPrice());
            cart5.setSkuId(skuList.get(i5).getId());
            cart5.setTitle(skuList.get(i5).getTitle());
            cart5.setSpuId(skuList.get(i5).getSpuId());
            cart5.setNum(1);
            skuList5.add(cart5);

            i1 += 10;
            i2 += 40;
            i3 += 10;
            i4 += 10;
            i5 += 10;
        }

        Map<String, List<Cart>> resultMap = new HashMap<>();
        resultMap.put("skus1", skuList1);
        resultMap.put("skus2", skuList2);
        resultMap.put("skus3", skuList3);
        resultMap.put("skus4", skuList4);
        resultMap.put("skus5", skuList5);
        return resultMap;

    }
}
